import React from 'react';
import { LangGraphChatUIImpl, WorkflowMessage } from '../lib/langgraph-chat-ui';
import { useMCP } from '../contexts/MCPContext';

export interface UseLangGraphChatUI {
  // 状态
  messages: WorkflowMessage[];
  answers: WorkflowMessage[];
  isLoading: boolean;
  isConfigured: boolean;
  hasMCPEnabled: boolean;
  status: string;
  
  // 方法
  sendMessage: (message: string) => Promise<void>;
  setApiKey: (apiKey: string) => void;
  setModelOverride: (model: string) => void;
  saveToStorage: () => Promise<void>;
  loadFromStorage: () => Promise<void>;
  resetWorkflowUI: () => void;
  toggleActionCollapse: (actionId: string) => void;
  toggleActionSection: (actionId: string, sectionId: string) => void;
}

export function useLangGraphChatUI(): UseLangGraphChatUI {
  const chatUIRef = React.useRef<LangGraphChatUIImpl | null>(null);

  if (!chatUIRef.current) {
    chatUIRef.current = new LangGraphChatUIImpl();
  }

  const chatUI = chatUIRef.current;
  const { setAgentStatus, setInitialized: setMCPInitialized } = useMCP();
  
  // 状态管理
  const [messages, setMessages] = React.useState<WorkflowMessage[]>([...chatUI.messages]);
  const [answers, setAnswers] = React.useState<WorkflowMessage[]>([...chatUI.answers]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [isConfigured, setIsConfigured] = React.useState(false);
  const [hasMCPEnabled, setHasMCPEnabled] = React.useState(false);
  const [statusMessage, setStatusMessage] = React.useState(chatUI.status);
  const handleToolsUpdate = React.useCallback((summary: Array<{ agentId: string; label: string; enabled: boolean; tools: string[] }>) => {
    summary.forEach((item) => {
      setAgentStatus(item.agentId, {
        enabled: item.enabled,
        toolsCount: item.tools.length,
        tools: item.tools,
        label: item.label
      });
    });
    setMCPInitialized(true);
  }, [setAgentStatus, setMCPInitialized]);

  // 初始化
  React.useEffect(() => {
    const init = async () => {
      setIsLoading(true);
      try {
        chatUI.onToolsUpdate = handleToolsUpdate;
        await chatUI.init();
        setIsConfigured(chatUI.isReady);
        setHasMCPEnabled(true); // LangGraph 版本默认启用 MCP
        setMessages([...chatUI.messages]);
        setAnswers([...chatUI.answers]);
        setStatusMessage(chatUI.status);
      } catch (error) {
        console.error('初始化失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    init();

    return () => {
      if (chatUI.onToolsUpdate === handleToolsUpdate) {
        chatUI.onToolsUpdate = undefined;
      }
    };
  }, [chatUI, handleToolsUpdate]);

  // 设置消息更新回调
  React.useEffect(() => {
    chatUI.onMessageUpdate = (newMessages) => {
      setMessages([...newMessages]);
    };

    chatUI.onStatusUpdate = (status) => {
      console.log('状态更新:', status);
      setStatusMessage(status);
    };

    chatUI.onAnswerUpdate = (cards) => {
      setAnswers([...cards]);
    };

    return () => {
      chatUI.onMessageUpdate = undefined;
      chatUI.onStatusUpdate = undefined;
      chatUI.onAnswerUpdate = undefined;
    };
  }, [chatUI]);

  // 发送消息
  const sendMessage = async (message: string): Promise<void> => {
    setIsLoading(true);
    try {
      await chatUI.sendMessage(message);
    } catch (error) {
      console.error('发送消息失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 配置管理
  const setApiKey = (apiKey: string): void => {
    chatUI.setApiKey(apiKey);
    setIsConfigured(chatUI.isReady);
  };

  const setModelOverride = (model: string): void => {
    chatUI.setModel(model);
  };

  const saveToStorage = async (): Promise<void> => {
    await chatUI.saveConfig();
  };

  const loadFromStorage = async (): Promise<void> => {
    await chatUI.loadUserConfig();
    setIsConfigured(chatUI.isReady);
  };

  // UI 控制
  const resetWorkflowUI = (): void => {
    chatUI.resetWorkflowUI();
    setMessages([...chatUI.messages]);
    setAnswers([...chatUI.answers]);
  };

  const toggleActionCollapse = (actionId: string): void => {
    chatUI.toggleActionCollapse(actionId);
  };

  const toggleActionSection = (actionId: string, sectionId: string): void => {
    chatUI.toggleActionSection(actionId, sectionId);
  };

  return {
    messages,
    answers,
    isLoading,
    isConfigured,
    hasMCPEnabled,
    status: statusMessage,
    sendMessage,
    setApiKey,
    setModelOverride,
    saveToStorage,
    loadFromStorage,
    resetWorkflowUI,
    toggleActionCollapse,
    toggleActionSection
  };
}
